package com.jt.ktdemo.utils

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.widget.ImageView
import kotlinx.android.synthetic.main.myinfo.view.*
import java.io.File
import java.io.OutputStream
import java.lang.Exception

class BitmapFileHelper{

    fun saveImageView(imv:ImageView,path:String):File{
        imv.isDrawingCacheEnabled = true
        var bitmap : Bitmap = Bitmap.createBitmap(imv.drawingCache)
        imv.isDrawingCacheEnabled = false
        var dirPath = path.substring(0,path.lastIndexOf("/")+1)

        var dir : File = File(dirPath)
        if(!dir.exists()){
            dir.mkdir()
        }

        var file = File(path)
        if(!file.exists()){
            file.createNewFile()
        }

        try{
            var fos: OutputStream = file.outputStream()
            bitmap.compress(Bitmap.CompressFormat.PNG,80,fos)
            fos.flush()
            fos.close()
        }catch (e:Exception){
        }
        return dir
    }

    /**
     * @param imgePath 图片路径
     * @param path 保存路径
     */
    fun savePath(imgePath:String,path:String):File{
        var bitmap:Bitmap = BitmapFactory.decodeStream(File(imgePath).inputStream())
        var dirPath = path.substring(0,path.lastIndexOf("/")+1)
        var dir : File = File(dirPath)
        if(!dir.exists()){
            dir.mkdir()
        }
        var file = File(path)
        if(!file.exists()){
            file.createNewFile()
        }

        try{
            var fos: OutputStream = file.outputStream()
            bitmap.compress(Bitmap.CompressFormat.PNG,80,fos)
            fos.flush()
            fos.close()
        }catch (e:Exception){
        }
        return dir
    }

    /**
     * 保存bitmap
     */
    fun saveBitmapMethod(bitmap:Bitmap,path:String):File{
        var dirPath = path.substring(0,path.lastIndexOf("/")+1)
        var dir : File = File(dirPath)
        if(!dir.exists()){
            dir.mkdir()
        }
        var file = File(path)
        if(!file.exists()){
            file.createNewFile()
        }

        try{
            var fos: OutputStream = file.outputStream()
            bitmap.compress(Bitmap.CompressFormat.PNG,80,fos)
            fos.flush()
            fos.close()
        }catch (e:Exception){
        }
        return dir
    }

    //字节读取图片文件
    fun readBitmapByByte(imv:ImageView,path:String){
        var bytes:ByteArray = File(path).readBytes()
        var bitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.size)
        imv.setImageBitmap(bitmap)
    }

    //读取图片文件
    fun readBitmapFileByStream(imv:ImageView,path:String){
        var bitmap = BitmapFactory.decodeStream(File(path).inputStream())
        imv.setImageBitmap(bitmap)
    }

    //路径读取图片文件
    fun readBitmapFIleByPath(imv:ImageView,path:String){
        var bitmap = BitmapFactory.decodeFile(path)
        imv.setImageBitmap(bitmap)
    }

}